package com.sptpc.exam;

import com.sptpc.exam.model.Question;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/score.do")
public class ScoreServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获得session中加载的试题
        List<Question> questions =
                (List<Question>)request.getSession().getAttribute("questions");

        // 自动判分
        int scores = 0;
        for (Question q: questions) {
            // 通过试题id参数获得用户的选择
            String userAnswer = request.getParameter(q.getId());
            if (userAnswer!=null && userAnswer.equals(q.getAnswer())) { // 完成本题，并回答正确
                scores += 33;
            }
        }
        request.setAttribute("total", scores);
        request.getRequestDispatcher("result.jsp").forward(request, response);
    }
}
